package com.itheima.dao.impl;

import com.itheima.dao.USerDao;
import com.itheima.domain.User;
import org.springframework.dao.DataAccessException;
import org.springframework.jdbc.core.BeanPropertyRowMapper;
import org.springframework.jdbc.core.JdbcTemplate;
import org.springframework.jdbc.core.PreparedStatementCreator;
import org.springframework.jdbc.support.GeneratedKeyHolder;

import java.sql.Connection;
import java.sql.PreparedStatement;
import java.sql.SQLException;
import java.util.List;

public class UserDaoImpl implements USerDao {

    private JdbcTemplate jdbcTemplate;
    public void setJdbcTemplate(JdbcTemplate jdbcTemplate) {
        this.jdbcTemplate = jdbcTemplate;
    }

    public List<User> findAll() {
        try {
            List<User> userList = jdbcTemplate.query("select * from sys_user", new BeanPropertyRowMapper<User>(User.class));
            return userList;
        } catch (DataAccessException e) {
            return null;
        }
    }

    public Long save(final User user) {
        //创建PreparedStatementCreator
        PreparedStatementCreator creator = new PreparedStatementCreator() {
            public PreparedStatement createPreparedStatement(Connection connection) throws SQLException {
                //使用原始jdbc完成PreparementStatement的组建
                PreparedStatement ps = connection.prepareStatement("insert into sys_user values (?,?,?,?,?)",PreparedStatement.RETURN_GENERATED_KEYS);
                ps.setObject(1,null);
                ps.setString(2,user.getUsername());
                ps.setString(3,user.getEmail());
                ps.setString(4,user.getPassword());
                ps.setString(5,user.getPhoneNum());
                return ps;
            }
        };
        //创建keyHolder
        GeneratedKeyHolder keyHolder = new GeneratedKeyHolder();
        jdbcTemplate.update(creator,keyHolder);
        //获得生成的主键
        long userId = keyHolder.getKey().longValue();
        return userId; //返回当前保存用户的id，该id是数据库自动生成的
    }

    public void saveUserRoleRel(Long userId, long[] roleIds) {
        for (long roleId : roleIds) {
            jdbcTemplate.update("insert into sys_user_role values (?,?)",userId,roleId);
        }
    }

    public void delUserRoleRel(Long userId) {
        jdbcTemplate.update("delete from sys_user_role where userId = ?",userId);
    }

    public void del(Long userId) {
        jdbcTemplate.update("delete from sys_user where id = ?",userId);
    }

    public User findByUsernameAndPassword(String username, String password) {
        try {
            User user = jdbcTemplate.queryForObject("select * from sys_user where username = ? and password = ?", new BeanPropertyRowMapper<User>(User.class), username, password);
            return user;
        } catch (DataAccessException e) {
            return null;
        }

    }


}
